package com.huiyin.ui.discuz;

import java.io.File;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.huiyin.AppContext;
import com.huiyin.R;
import com.huiyin.UIHelper;
import com.huiyin.api.URLs;
import com.huiyin.js.JsInterface;
import com.huiyin.js.JsInterface.WebViewClientClickListener;
import com.huiyin.ui.classic.ProductsDetailActivity;
import com.huiyin.utils.FileUtils;
import com.huiyin.utils.LogUtil;

/**
 * 论坛
 * @author zhyao
 *
 */
// add by zhyao @2015/7/8
public class DiscuzBBSFragment extends Fragment{

	private static final String TAG = "DiscuzBBSFragment";
	
	private WebView mWebView;
	/**
	 * Java与JS交互接口
	 */
	private JsInterface jsInterface = new JsInterface();
	
	public static final int FILECHOOSER_RESULTCODE = 1;
	/**
	 * 照相
	 */
	private static final int REQ_CAMERA = FILECHOOSER_RESULTCODE+1;
	
	/**
	 * 相册
	 */
	private static final int REQ_CHOOSE = REQ_CAMERA+1;
	/**
	 * 图片回调地址
	 */
	private ValueCallback<Uri> mUploadMessage;
	/**
	 * 相册图片保存路径
	 */
	private String compressPath = "";
	/**
	 * 拍照图片保存路径
	 */
	private String imagePaths;
	/**
	 * 拍照图片Uri
	 */
	private Uri cameraUri;
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.discuz_bbs_layout, null);

		initViews(rootView);
		
		if(AppContext.userId != null) {
			loadUrl();
		}
	
		return rootView;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		
	
	}
	
	@TargetApi(Build.VERSION_CODES.JELLY_BEAN) 
	private void initViews(View rootView) {
		mWebView = (WebView) rootView.findViewById(R.id.discuz_web);
		WebSettings webSettings = mWebView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		webSettings.setAllowFileAccess(true);
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
			webSettings.setAllowFileAccessFromFileURLs(true);
		}
		webSettings.setAllowContentAccess(true);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setNeedInitialFocus(true);
		webSettings.setDatabaseEnabled(true);
		webSettings.setDomStorageEnabled(true);
		mWebView.addJavascriptInterface(jsInterface, "JSInterface");
		mWebView.setWebChromeClient(new MyWebChromeClient());
		mWebView.setWebViewClient(new WebViewClient(){
			
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
				Log.d(TAG, "DiscuzBBSFragemt : onPageStarted");
				//UIHelper.showLoadDialog(getActivity());
			}
			
			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				Log.d(TAG, "DiscuzBBSFragemt : onPageFinished");
				//UIHelper.cloesLoadDialog();
			}
			
			@Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.d(TAG, "shouldOverrideUrlLoading : url = " + url);
				if (url.startsWith("tel:")) { 
                    Intent intent = new Intent(Intent.ACTION_DIAL,
                            Uri.parse(url)); 
                    startActivity(intent); 
                } 
				else if (url != null) {
					if(url.contains("share.baidu.com")) {
						Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
					    startActivity(i);					
					}
					else {
						view.loadUrl(url);
					}
				}
				else {
					 // 使用自己的WebView组件来响应Url加载事件，而不是使用默认浏览器器加载页面
	                mWebView.loadUrl(url);
				}
                // 消耗掉这个事件。Android中返回True的即到此为止吧,事件就会不会冒泡传递了，我们称之为消耗掉
                return true;
            }
		});
		jsInterface.setWebViewClientClickListener(new WebViewClientClickListener() {
			
			@Override
			public void wvHasClickEnvent(String action, String args) {
				LogUtil.d(TAG, "wvHasClickEnvent : action = " + action);
				LogUtil.d(TAG, "wvHasClickEnvent : args = " + args);
				JSONArray jsonArray;
				JSONObject jsonObject;
				Intent intent;
				//跳转到附近汇银
				if("startNearShop".equals(action)) {
					//startActivity(new Intent(getActivity(), NearTheShopActivityNew.class));
				}
				//跳转详情
				else if("startGoodDetail".equals(action)) {
					try {
						jsonArray = new JSONArray(args);
						jsonObject = (JSONObject) jsonArray.get(0);
						String className = jsonObject.getString("class");
						String storeId = jsonObject.getString("storeId");
						String goodsNo = jsonObject.getString("goodsNo");
						String goodsId = jsonObject.getString("goodsId");
						intent = new Intent(getActivity(), Class.forName(className));
						intent.putExtra(ProductsDetailActivity.STORE_ID, storeId);
						intent.putExtra(ProductsDetailActivity.GOODS_NO, goodsNo);
						intent.putExtra(ProductsDetailActivity.BUNDLE_KEY_GOODS_ID, goodsId);
						
						startActivity(intent);
					} catch (JSONException e1) {
						e1.printStackTrace();
					}
					catch (ClassNotFoundException e) {
						e.printStackTrace();
					}
				}
			}
		});
		
		
	}
	
	public void loadUrl() {
//		LoginInfo mLoginInfo = AppContext.getLoginInfo(getActivity());
//		
//		if(mLoginInfo != null) {
//			mWebView.loadUrl(String.format(URLs.loginDiscuz, mLoginInfo.userName, mLoginInfo.psw));
//		}
//		Log.d(TAG, "http://192.168.200.109:8080/x5/$v6079bbb51f274818846f9c9334d659b0$lzh_CN$sdesktop$d/UI2/hylehumall/www/index.html");
//		mWebView.loadUrl("http://192.168.19.21:8083/community/www/index.html");
		mWebView.loadUrl(URLs.community);
	}
	
//	protected boolean isCreated = false;
//	@Override
//	public void onCreate(Bundle savedInstanceState) {	
//		super.onCreate(savedInstanceState);	// ...	
//		isCreated = true;
//	}
//	
//	/** 
//	 *  ViewPager中的Fragment是否真实可见  
//	 **/
//	@Override
//	public void setUserVisibleHint(boolean isVisibleToUser) {	
//		super.setUserVisibleHint(isVisibleToUser);	
//		if (!isCreated) {		
//			return;	
//		}	
//		if (isVisibleToUser) {	
//			pageStart();	
//		}
//		else 
//		{	
//			pageEnd();
//		}
//	}
//
//	private void pageEnd() {
//		
//	}
//
//	private void pageStart() {
//		
//	}
//	
	
	private class MyWebChromeClient extends WebChromeClient {

		// For Android 3.0+
		public void openFileChooser(ValueCallback<Uri> uploadMsg,
				String acceptType) {
			if (mUploadMessage != null)
				return;
			mUploadMessage = uploadMsg;
			selectImage();
			// Intent i = new Intent(Intent.ACTION_GET_CONTENT);
			// i.addCategory(Intent.CATEGORY_OPENABLE);
			// i.setType("*/*");
			// startActivityForResult( Intent.createChooser( i, "File Chooser"
			// ), FILECHOOSER_RESULTCODE );
		}

		// For Android < 3.0
		public void openFileChooser(ValueCallback<Uri> uploadMsg) {
			openFileChooser(uploadMsg, "");
		}

		// For Android > 4.1.1
		public void openFileChooser(ValueCallback<Uri> uploadMsg,
				String acceptType, String capture) {
			openFileChooser(uploadMsg, acceptType);
		}

	}
	
	/**
	 * 检查SD卡是否存在
	 * 
	 * @return
	 */
	public final boolean checkSDcard() {
		boolean flag = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
		if (!flag) {
			UIHelper.showToast("请插入手机存储卡再使用本功能");
		}
		return flag;
	}

	/**
	 * 选择图片方式:拍照和相册
	 */
	protected final void selectImage() {
		if (!checkSDcard())
			return;
		String[] selectPicTypeStr = { "拍照", "相册"};
		new AlertDialog.Builder(getActivity()).setItems(selectPicTypeStr,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						// 相机拍摄
						case 0:
							openCarcme();
							break;
						// 手机相册
						case 1:
							chosePic();
							break;
						default:
							break;
						}
						compressPath = Environment
								.getExternalStorageDirectory().getPath()
								+ "/huiyinlehu/temp";
						new File(compressPath).mkdirs();
						compressPath = compressPath + File.separator +  (System.currentTimeMillis() + ".jpg");
					}
				})
//				.setCancelable(false)
				.setOnCancelListener(new OnCancelListener() {
					
					@Override
					public void onCancel(DialogInterface dialog) {
						if (null == mUploadMessage)
							return;
						mUploadMessage.onReceiveValue(null);
						mUploadMessage = null;
					}
				})
				.show();
	}

	

	/**
	 * 打开照相机
	 */
	private void openCarcme() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		imagePaths = Environment.getExternalStorageDirectory().getPath()
				+ "/huiyinlehu/temp/" + (System.currentTimeMillis() + ".jpg");
		// 必须确保文件夹路径存在，否则拍照后无法完成回调
		File vFile = new File(imagePaths);
		if (!vFile.exists()) {
			File vDirPath = vFile.getParentFile();
			vDirPath.mkdirs();
		} else {
			if (vFile.exists()) {
				vFile.delete();
			}
		}
		cameraUri = Uri.fromFile(vFile);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
		startActivityForResult(intent, REQ_CAMERA);
	}

	/**
	 * 拍照结束后
	 */
	private void afterOpenCamera() {
		File f = new File(imagePaths);
		addImageGallery(f);
		//File newFile = FileUtils.compressFile(f.getPath(), compressPath);
	}

	/** 解决拍照后在相册中找不到的问题 */
	private void addImageGallery(File file) {
		ContentValues values = new ContentValues();
		values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
		values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
		getActivity().getContentResolver().insert(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
	}

	/**
	 * 本地相册选择图片
	 */
	private void chosePic() {
		FileUtils.delFile(compressPath);
//		Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); // "android.intent.action.GET_CONTENT"
//		String IMAGE_UNSPECIFIED = "image/*";
//		innerIntent.setType(IMAGE_UNSPECIFIED); // 查看类型
//		Intent wrapperIntent = Intent.createChooser(innerIntent, null);
//		startActivityForResult(wrapperIntent, REQ_CHOOSE);
		
		Intent intent = new Intent(
                Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(intent, REQ_CHOOSE);
	}

	/**
	 * 选择照片后结束
	 * 
	 * @param data
	 */
	private Uri afterChosePic(Intent data) {

		// 获取图片的路径：
		String[] proj = { MediaStore.Images.Media.DATA };
		// 好像是android多媒体数据库的封装接口，具体的看Android文档
		@SuppressWarnings("deprecation")
		Cursor cursor = getActivity().managedQuery(data.getData(), proj, null, null, null);
		if (cursor == null) {
			UIHelper.showToast("上传的图片仅支持png或jpg格式");
			return null;
		}
		// 按我个人理解 这个是获得用户选择的图片的索引值
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		// 将光标移至开头 ，这个很重要，不小心很容易引起越界
		cursor.moveToFirst();
		// 最后根据索引值获取图片路径
		String path = cursor.getString(column_index);
		if (path != null
				&& (path.endsWith(".png") || path.endsWith(".PNG")
						|| path.endsWith(".jpg") || path.endsWith(".JPG"))) {
			File newFile = FileUtils.compressFile(path, compressPath);
			return Uri.fromFile(newFile);
		} else {
			UIHelper.showToast("上传的图片仅支持png或jpg格式");
		}
		return null;
	}
	


	/**
	 * 返回文件选择
	 */
	public void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		// if (requestCode == FILECHOOSER_RESULTCODE) {
		// if (null == mUploadMessage)
		// return;
		// Uri result = intent == null || resultCode != RESULT_OK ? null
		// : intent.getData();
		// mUploadMessage.onReceiveValue(result);
		// mUploadMessage = null;
		// }
		Log.d(TAG, "requestCode = " + requestCode + "  resultCode = " + resultCode + "   intent = " + intent);
		if (null == mUploadMessage) 
			return;
	
		Uri uri = null;
		if (requestCode == REQ_CAMERA) {
			afterOpenCamera();
			uri = cameraUri;
		} else if (requestCode == REQ_CHOOSE && null != intent) {
			uri = afterChosePic(intent);
		} else {
			uri = null;
		}
		mUploadMessage.onReceiveValue(uri);
		mUploadMessage = null;
		super.onActivityResult(requestCode, resultCode, intent);
	}
	
	
	
	
	
	
}
